<?php
// app/Console/Commands/ManageIpBlacklist.php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class ManageIpBlacklist extends Command
{
    protected $signature = 'ip:blacklist {action} {ip?}';
    protected $description = '管理IP黑名单';

    public function handle()
    {
        $action = $this->argument('action');
        $ip = $this->argument('ip');

        switch ($action) {
            case 'list':
                $this->listBlacklist();
                break;
            case 'add':
                $this->addToBlacklist($ip);
                break;
            case 'remove':
                $this->removeFromBlacklist($ip);
                break;
            case 'clear':
                $this->clearBlacklist();
                break;
            default:
                $this->error('无效的操作');
        }
    }

    private function listBlacklist()
    {
        $blacklist = Redis::smembers('ip:blacklist');
        $this->info('黑名单IP列表:');
        foreach ($blacklist as $ip) {
            $this->line($ip);
        }
    }

    private function addToBlacklist($ip)
    {
        Redis::sadd('ip:blacklist', $ip);
        $this->info("IP {$ip} 已添加到黑名单");
    }

    private function removeFromBlacklist($ip)
    {
        Redis::srem('ip:blacklist', $ip);
        $this->info("IP {$ip} 已从黑名单移除");
    }

    private function clearBlacklist()
    {
        Redis::del('ip:blacklist');
        $this->info('黑名单已清空');
    }
}
